package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.CardStatusDetialAdapter;
import com.github.postsanf.yinian.bean.YNComment;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommentResponse;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 动态详情
 */
public class CardStatusCommentActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView mRecyclerView;
    private CardStatusDetialAdapter mAdapter;
    private List<YNComment> mCommentList = new ArrayList<>();
    private YNStatus mCurStatus;
    private int groupid;
    private Button btn_comment;
    private EditText et_comment;
    private boolean isSending = false;                  //  是否在发布评论  默认 否
    private String cContent;
    private YNUser commentedUser;
    private AlertDialog alertDialog;
    private YNComment mCommentItem;
    private YNUser sys = new YNUser();
    private ImageView comment_tip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_cardstatus_comment);
        initDatas();
        initView();
    }

    private void initDatas() {
        mCurStatus = YNSingleton.getInstance().getCurStatus();
        groupid = application.getCurGid();
        if (getIntent() != null) {
            mCommentList = mCurStatus.getComments();
        }
        sys.setUserid(CommonConstants.SYSTEM_ID);
        commentedUser = sys;
    }

    private void initView() {
        findViewById(R.id.top_back).setOnClickListener(this);
        comment_tip = (ImageView) findViewById(R.id.comment_tip);
        btn_comment = (Button) findViewById(R.id.btn_comment);
        et_comment = (EditText) findViewById(R.id.et_comment);
        btn_comment.setOnClickListener(this);
        //评论列表
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_status_detail_list);
        WrapContentLinearLayoutManager wlinearLayoutManager = new WrapContentLinearLayoutManager(this);
        wlinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(wlinearLayoutManager);
        mAdapter = new CardStatusDetialAdapter(this, mCommentList, groupid);
        mRecyclerView.setAdapter(mAdapter);
        //为每个item增加响应事件
        mAdapter.setOnItemClickListener(new CardStatusDetialAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, YNComment data) {
                mCommentItem = data;
                if (mCommentItem.getCommentUser().getUserid() == application.getCurID() || String.valueOf(application.getCurID()).equals(getString(R.string.numberofme))) {
                    popDelComment();
                } else {
                    publishComment();
                }
            }
        });
    }

    private void popDelComment() {
        View sexView = View.inflate(this, R.layout.yn_comment_del, null);
        LinearLayout ll_ret = (LinearLayout) sexView.findViewById(R.id.ll_comment_ret);
        LinearLayout ll_del = (LinearLayout) sexView.findViewById(R.id.ll_comment_del);
        alertDialog = new AlertDialog.Builder(this).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(sexView);
        WindowManager.LayoutParams layout = alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 32 * 2);
        alertDialog.getWindow().setAttributes(layout);
        ll_ret.setVisibility(View.GONE);
        // 回复
//        ll_ret.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                publishComment();
//                alertDialog.dismiss();
//            }
//        });
        // 删除
        ll_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delComment(mCommentItem.getCid());
                alertDialog.dismiss();
            }
        });
    }

    // 删除评论
    private void delComment(final String comId) {
        if (StringUtils.isEmptyString(comId)) {
            showToast("删除失败");
            return;
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_DEL_COMMENT, comId);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDelComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelComment = gson.fromJson(s, YNCommonResponse.class);
                        if (resDelComment != null && ReqUtils.isSuccess(resDelComment.getCode())) {
                            for (int i = 0; i < mCurStatus.getComments().size(); i++) {
                                if (comId.equals(mCurStatus.getComments().get(i).getCid())) {
                                    mCurStatus.getComments().remove(i);
                                    mAdapter.notifyItemRemoved(i + 1);
//                                    mRecyclerView.scrollToPosition(i);
                                    // 通知评论更新
                                    Intent mIntent = new Intent(ACTIONs.actionComment);
                                    sendBroadcast(mIntent);
                                }
                            }
                            if (mCurStatus.getComments().size() == 0) {
                                comment_tip.setVisibility(View.VISIBLE);
                            } else {
                                comment_tip.setVisibility(View.GONE);
                            }
                        } else {
                            showToast(resDelComment.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void publishComment() {
        commentedUser = mCommentItem.getCommentUser();
        et_comment.setHint("//回复" + mCommentItem.getCommentUser().getUnickname() + ":");
        et_comment.setFocusable(true);
        et_comment.setFocusableInTouchMode(true);
        et_comment.requestFocus();
        et_comment.findFocus();
    }

    // 发表评论
    private void doComment() {
        if (checkComment() && !isSending) {
            isSending = true;       // 更改状态
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_COMMENT_USER_ID, String.valueOf(application.getCurID()));
            mParam.put(CommonConstants.YNS_COMMENTED_USER_ID, String.valueOf(commentedUser.getUserid()));
            mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(mCurStatus.getEid()));
            mParam.put(CommonConstants.YNS_CONTENT, cContent);
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynSendComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            YNCommentResponse resSendComment = gson.fromJson(s, YNCommentResponse.class);
                            if (resSendComment != null && ReqUtils.isSuccess(resSendComment.getCode())) {
                                YNComment createComment = resSendComment.getData().get(0);
                                createComment.setCcontent(cContent);
                                application.getCurUser().setUserid(application.getCurID());
                                createComment.setCommentUser(application.getCurUser());
                                createComment.setCommentedUser(commentedUser);
                                createComment.setCtime(DateFormat.format("yyyy-MM-dd  HH:mm:ss", new Date()).toString());
                                mCurStatus.getComments().add(mCurStatus.getComments().size(), createComment);
                                mAdapter.notifyItemInserted(mCurStatus.getComments().size());
                                mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
                                // 通知评论更新
                                Intent mIntent = new Intent(ACTIONs.actionComment);
                                sendBroadcast(mIntent);
                                et_comment.setHint("说点什么");
                                et_comment.setText("");
                                // 还原当前对系统的评论
                                commentedUser = sys;
                            } else {
                                showToast(resSendComment.getMsg());
                            }
                            // 还原状态
                            isSending = false;
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(CommonConstants.YN_NET_LINK);
                            // 还原状态
                            isSending = false;
                        }
                    });
            liteHttp.executeAsync(req);
        }
    }

    // 检测评论
    private Boolean checkComment() {
        cContent = et_comment.getText().toString().trim();
        if (StringUtils.isEmptyString(cContent)) {
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_comment:
                doComment();
                break;
            case R.id.top_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
